// 数据验证中间件
const { validationResult } = require('express-validator');

// 验证结果处理
const validate = (req, res, next) => {
  const errors = validationResult(req);
  if (!errors.isEmpty()) {
    return res.json({
      success: false,
      message: '参数验证失败',
      errors: errors.array()
    });
  }
  next();
};

// 通用验证规则
const validationRules = {
  // 验证订单号
  orderNo: (value) => {
    if (!value || typeof value !== 'string') {
      throw new Error('订单号格式不正确');
    }
    return true;
  },

  // 验证商品ID
  productId: (value) => {
    const id = parseInt(value);
    if (!id || id <= 0) {
      throw new Error('商品ID无效');
    }
    return true;
  },

  // 验证OpenID
  openid: (value) => {
    if (!value || typeof value !== 'string' || value.length < 10) {
      throw new Error('OpenID格式不正确');
    }
    return true;
  }
};

module.exports = {
  validate,
  validationRules
};

